package com.mihuxiaobaigao.ai.Aop;

import com.alibaba.fastjson.JSON;

import com.mihuxiaobaigao.ai.Mapper.OperateLogMapper;
import com.mihuxiaobaigao.ai.pojo.OperateLog;
import com.mihuxiaobaigao.ai.pojo.Product;
import com.mihuxiaobaigao.ai.pojo.ProductDTO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.mihuxiaobaigao.ai.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        /*String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtils.parseJWT(jwt);
        String operateUser = (String) claims.get("username");*/
        LocalDateTime operateTime = LocalDateTime.now();
        //String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        //Object[] product = joinPoint.getArgs();
        Object[] args = joinPoint.getArgs();
        String name = null;
        Integer count = null;
        if (methodName.equals("deleteByName")) {
            name = args[0].toString();
        }else if(methodName.equals("add") || methodName.equals("take")){
            name = args[0].toString();
            count = Integer.parseInt(args[1].toString());
        }else if(methodName.equals("insert")){
            ProductDTO productDTO = new ProductDTO();
            productDTO = (ProductDTO) args[0];
            name = productDTO.getProduct().getName();
            count = productDTO.getProduct().getCount();
        }

        //System.out.println(product[0].toString());



        long startTime = System.currentTimeMillis();
        try {
            Object result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            String resultValues = JSON.toJSONString(result);
            Long spendTime = endTime - startTime;

            OperateLog operateLog = new OperateLog
                    (null,operateTime,methodName,resultValues, spendTime,name,count);
            log.info("AOP记录操作日志：{}",operateLog);

            operateLogMapper.insert(operateLog);

            return result;
        } catch (Throwable e) {
            System.out.println("AOP出现错误，进行手动事务回滚");
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return null;
    }
}
